package com.cblz.bd.server.frontend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cblz.bd.common.core.exception.BdAdminException;
import com.cblz.bd.common.core.exception.ValidateCodeException;
import com.cblz.bd.server.frontend.entity.BaUser;
import com.cblz.bd.server.frontend.entity.vo.BaUserLoginRegisterVO;
import com.cblz.bd.server.frontend.mapper.BaUserMapper;
import com.cblz.bd.server.frontend.service.BaUserService;
import com.cblz.bd.server.utils.BcryptUtil;
import com.cblz.bd.server.utils.BdCaptchaUtil;
import com.cblz.bd.server.utils.StpUserUtil;
import io.vavr.control.Option;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author yanjieping
 * @description 针对表【ba_user(会员表)】的数据库操作Service实现
 * @createDate 2022-11-04 15:09:54
 */
@Service("baUserService")
@RequiredArgsConstructor
public class BaUserServiceImpl extends ServiceImpl<BaUserMapper, BaUser> implements BaUserService {

    private final BdCaptchaUtil bdCaptchaUtil;

    /**
     * 外部用户登录
     *
     * @param loginRegisterVO 登录信息
     * @return Token信息
     */
    @Override
    public Map<String, Object> login(BaUserLoginRegisterVO loginRegisterVO) throws ValidateCodeException {
        bdCaptchaUtil.check(loginRegisterVO.getKey(), loginRegisterVO.getCaptcha());

        BaUser baUser = Option.of(getOne(new LambdaQueryWrapper<BaUser>().eq(BaUser::getUsername, loginRegisterVO.getUsername()))).getOrElseThrow(() -> {
            // 删除验证码
            bdCaptchaUtil.delCaptcha(loginRegisterVO.getKey());
            throw new BdAdminException("该用户名未注册");
        });
        if (BcryptUtil.decrypt(loginRegisterVO.getPassword(), baUser.getPassword())) {
            // 登录,是否为记住我模式
            StpUserUtil.login(baUser.getId(), loginRegisterVO.getKeep());
            StpUserUtil.getLoginId();
            // 获取token信息
            loginRegisterVO.setToken(StpUserUtil.getTokenInfo().getTokenValue());
            // 查询用户信息
            BeanUtil.copyProperties(baUser, loginRegisterVO);

            // 跳转路由
            return Map.of("userinfo", loginRegisterVO, "routePath", "/");
        }
        // 用户名密码不正确就删除验证码，让其失效
        bdCaptchaUtil.delCaptcha(loginRegisterVO.getKey());
        return Map.of();
    }
}




